/**
 * 积分预测页面组件
 * 基于用户历史数据和消费习惯预测未来积分变化趋势，帮助用户制定积分使用计划
 */
import React, { useState, useEffect } from 'react'
import { View, Text, Picker, Button, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useAppContext } from '../../store'
import { pointsUtils } from '../../utils/pointsUtils'
import pointsConfig from '../../config/pointsConfig'
import NetworkStatus from '../../components/NetworkStatus'
import './forecast.scss'

/**
 * 预测项目接口
 */
interface ForecastItem {
  title: string;        // 预测项目标题
  description: string;  // 预测项目描述
  points: number;       // 预测积分数量
  icon: string;         // 项目图标
}

/**
 * 积分预测页面组件
 * 提供积分变化趋势分析、未来预测、使用建议等功能
 */
const PointsForecast: React.FC = () => {
  const { state } = useAppContext()
  
  // 网络状态
  const [isOnline, setIsOnline] = useState(true)
  // 会员信息
  const [memberInfo, setMemberInfo] = useState<any>(null)
  // 预测项目列表
  const [forecastItems, setForecastItems] = useState<ForecastItem[]>([])
  // 预测总积分
  const [totalForecast, setTotalForecast] = useState(0)
  // 消费金额
  const [spendAmount, setSpendAmount] = useState('100')
  // 预测天数
  const [forecastDays, setForecastDays] = useState('30')
  // 加载状态
  const [loading, setLoading] = useState(false)
  
  // 预测天数选项
  const dayOptions = ['7', '14', '30', '60', '90']
  
  /**
   * 组件挂载时获取会员信息
   */
  useEffect(() => {
    if (state.currentUser?.id) {
      fetchMemberInfo()
    } else {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      Taro.navigateBack()
    }
  }, [state.currentUser])
  
  /**
   * 当预测参数变化时，更新预测结果
   */
  useEffect(() => {
    if (state.currentUser?.id && memberInfo) {
      calculateForecast()
    }
  }, [spendAmount, forecastDays, memberInfo])
  
  /**
   * 获取会员信息
   */
  const fetchMemberInfo = async () => {
    if (!state.currentUser?.id) return
    
    setLoading(true)
    try {
      const info = await pointsUtils.getUserMemberInfo(state.currentUser.id)
      setMemberInfo(info)
    } catch (error) {
      console.error('获取会员信息失败:', error)
      Taro.showToast({
        title: '获取会员信息失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }
  
  /**
   * 计算积分预测
   * 基于用户消费习惯和会员等级计算未来积分获取情况
   */
  const calculateForecast = () => {
    if (!memberInfo) return
    
    const days = parseInt(forecastDays)
    const amount = parseFloat(spendAmount)
    
    if (isNaN(days) || isNaN(amount)) return
    
    const items: ForecastItem[] = []
    let total = 0
    
    // 1. 消费积分 - 基于每日消费金额计算
    const basePoints = Math.floor(amount * pointsConfig.POINTS_EXCHANGE_RATE.MONEY_TO_POINTS)
    const multiplier = memberInfo.pointsMultiplier
    const consumptionPoints = Math.floor(basePoints * multiplier)
    
    items.push({
      title: '消费积分',
      description: `每消费${amount}元 x ${days}天`,
      points: consumptionPoints * days,
      icon: '💰'
    })
    total += consumptionPoints * days
    
    // 2. 评价奖励 - 假设每3天评价一次
    const ratingCount = Math.floor(days / 3)
    if (ratingCount > 0) {
      const ratingPoints = Math.floor(pointsConfig.POINTS_REWARDS.RATING * multiplier) * ratingCount
      
      items.push({
        title: '评价奖励',
        description: `${ratingCount}次评价`,
        points: ratingPoints,
        icon: '⭐'
      })
      total += ratingPoints
    }
    
    // 3. 分享奖励 - 假设每5天分享一次
    const sharingCount = Math.floor(days / 5)
    if (sharingCount > 0) {
      const sharingPoints = Math.floor(pointsConfig.POINTS_REWARDS.SHARING * multiplier) * sharingCount
      
      items.push({
        title: '分享奖励',
        description: `${sharingCount}次分享`,
        points: sharingPoints,
        icon: '📢'
      })
      total += sharingPoints
    }
    
    // 4. 连续下单奖励 - 假设每2天下单一次
    const orderCount = Math.floor(days / 2)
    if (orderCount > 0) {
      const consecutivePoints = Math.floor(pointsConfig.POINTS_REWARDS.CONSECUTIVE_ORDER * multiplier) * orderCount
      
      items.push({
        title: '连续下单',
        description: `${orderCount}天连续下单`,
        points: consecutivePoints,
        icon: '📆'
      })
      total += consecutivePoints
    }
    
    // 5. 生日奖励 - 如果预测周期超过30天且会员等级较高
    if (days >= 30 && memberInfo.level >= 2) {
      const birthdayPoints = 100 * multiplier
      
      items.push({
        title: '生日奖励',
        description: '预计生日奖励',
        points: birthdayPoints,
        icon: '🎂'
      })
      total += birthdayPoints
    }
    
    // 更新预测结果
    setForecastItems(items)
    setTotalForecast(total)
  }
  
  /**
   * 处理消费金额输入变化
   * @param e 输入事件
   */
  const handleAmountChange = (e) => {
    const value = e.detail.value
    setSpendAmount(value)
  }
  
  /**
   * 处理预测天数选择变化
   * @param e 选择事件
   */
  const handleDaysChange = (e) => {
    const index = parseInt(e.detail.value)
    setForecastDays(dayOptions[index])
  }
  
  /**
   * 处理网络状态变化
   * @param online 是否在线
   */
  const handleNetworkStatusChange = (online: boolean) => {
    setIsOnline(online)
  }
  
  return (
    <View className='points-forecast'>
      {/* 网络状态提示组件 */}
      <NetworkStatus onStatusChange={handleNetworkStatusChange} />
      
      {/* 会员信息展示 */}
      {memberInfo && (
        <View className='member-info'>
          <View className='level-info'>
            <Text className='level-name'>{memberInfo.name}</Text>
            <Text className='multiplier'>积分倍率: x{memberInfo.pointsMultiplier}</Text>
          </View>
          
          {/* 下一等级信息 */}
          {memberInfo.nextLevel && (
            <View className='next-level'>
              <Text className='next-level-text'>
                距离{memberInfo.nextLevel.name}还需{memberInfo.nextLevel.pointsNeeded}积分
              </Text>
            </View>
          )}
        </View>
      )}
      
      {/* 预测参数设置 */}
      <View className='forecast-params'>
        <View className='param-item'>
          <Text className='param-label'>日均消费金额 (元)</Text>
          <Input
            className='param-input'
            type='digit'
            value={spendAmount}
            onInput={handleAmountChange}
            placeholder='请输入金额'
          />
        </View>
        
        <View className='param-item'>
          <Text className='param-label'>预测天数</Text>
          <Picker
            mode='selector'
            range={dayOptions}
            onChange={handleDaysChange}
            value={dayOptions.indexOf(forecastDays)}
          >
            <View className='picker-value'>
              {forecastDays}天
              <Text className='picker-arrow'>▼</Text>
            </View>
          </Picker>
        </View>
      </View>
      
      {/* 预测结果展示 */}
      <View className='forecast-results'>
        <View className='results-header'>
          <Text className='header-title'>预计可获得积分</Text>
          <Text className='header-total'>{totalForecast}</Text>
        </View>
        
        {/* 预测项目列表 */}
        <View className='results-list'>
          {forecastItems.map((item, index) => (
            <View key={index} className='forecast-item'>
              <View className='item-icon'>{item.icon}</View>
              <View className='item-info'>
                <Text className='item-title'>{item.title}</Text>
                <Text className='item-desc'>{item.description}</Text>
              </View>
              <Text className='item-points'>+{item.points}</Text>
            </View>
          ))}
        </View>
        
        {/* 预测说明 */}
        <View className='forecast-note'>
          <Text className='note-text'>
            注：此预测基于您当前的会员等级和积分规则，实际获得的积分可能因多种因素而有所不同。
          </Text>
        </View>
      </View>
      
      {/* 积分规则链接 */}
      <View className='rules-link'>
        <Button 
          className='link-button'
          onClick={() => Taro.navigateTo({ url: '/pages/points/rules' })}
        >
          查看积分规则
        </Button>
      </View>
      
      {/* 离线状态提示 */}
      {!isOnline && (
        <View className='offline-warning'>
          <Text>您当前处于离线状态，部分功能可能受限</Text>
        </View>
      )}
    </View>
  )
}

export default PointsForecast 